<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>在线客服</title>
<link rel="stylesheet" href="/static/layim/css/layui.css">
<script src="/static/layim/layui.js"></script>
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/swfobject.js"></script>
<script type="text/javascript" src="/static/js/web_socket.js"></script>
</head>
<body>
<script>
	WEB_SOCKET_SWF_LOCATION = "/static/swf/WebSocketMain.swf";
    var
        ws,
        token     = '{$open_data.user_token}',
        user_name = '{$open_data.user_name}',
        service_id = '{$open_data.service_id}',
        service_name = '{$open_data.service_name}',
        service_avatar = '{$open_data.service_avatar}';
    var layer = layui.layer;

    //初始化连接socket
    function ini_set() {
        ws = new WebSocket("ws://" + document.domain + ":7272");
        ws.onopen = initServer;
        ws.onmessage = onMessage;
        ws.onclose = function () {
            //ini_set();
        };
        ws.onerror = function () {
            console.log('连接在线客服失败');
            //ini_set();
        };
    }

    function initServer() {
         var init_data = '{"type":"open_service", "token":"' + token + '"}';
         ws.send(init_data);
    }

    function onMessage(e) {
        var data = evil(e.data);
        if(data.type == 'friend')
        {
            layui.use('layim', function(layim){
                var layim = layui.layim;
                layim.getMessage(data);
            })
        }
    }

    //layim核心界面显示
    layui.use('layim', function(layim){
        var layim = layui.layim;
        //初始化聊天界面
        layim.config({
            init: {
              mine: {
                "username": "我" //我的昵称
                ,"id": ""+token+"" //我的ID
                ,"status": "online" //在线状态 online：在线、hide：隐身
                ,"avatar": "{$open_data.avatar}" //我的头像
              }
            }
            ,brief: true //是否简约模式（如果true则不显示主面板）
        }).chat({
            name: ''+service_name+''
            ,type: 'friend'
            ,avatar: ''+service_avatar+''
            ,id: service_id
        });

        //监听发送消息
        layim.on('sendMessage', function(res){
            var mine = res.mine;
            var to   = res.to;
            var message_data = {};
            message_data['type'] = 'service_message';
            message_data['receive_id'] = service_id;  //接收消息人的id
            message_data['from_name']  = user_name;        //发送人名称
            message_data['from_head']  = '{$open_data.avatar}'; //发送人头像
            message_data['message_content'] = mine.content; 
            message_data['token']    = token; 
            var json_message_data = JSON.stringify( message_data );
            ws.send(json_message_data);
        })
    });

    function evil(fn) {
        var Fn = Function;  
        return new Fn('return ' + fn)();
    }


    ini_set();
</script>
</body>
</html>